-module(mysql_test).
-compile(export_all).

-define(DB, mysql_dispatcher).
-define(DB_POOL, mysql_conn).
-define(DB_HOST, "192.168.1.100").
-define(DB_PORT, 3306).
-define(DB_USER, "root").
-define(DB_PASS, "111111").
-define(DB_NAME, "test").
-define(DB_ENCODE, utf8).

conn()->
    mysql:start_link(?DB, ?DB_POOL, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, fun(_, _, _, _) -> ok end, ?DB_ENCODE),
    mysql:connect(?DB, ?DB_POOL, ?DB_HOST, ?DB_PORT, ?DB_USER, ?DB_PASS, ?DB_NAME, ?DB_ENCODE, true),
    mysql:fetch(?DB_POOL, <<"drop table if exists test">>),
	mysql:fetch(?DB_POOL, <<"create table test (id int not null auto_increment,row varchar(50) not null,r int not null, primary key (id)) engine = myisam">>),
%%     mysql:fetch(?DB, <<"truncate table test">>),
    ok.

test() ->
    mysql:fetch(?DB_POOL, <<"truncate table test">>),
    mysql:fetch(?DB_POOL, <<"begin">>),
    F = fun() ->
		db_mysql:insert(test, [{row, "我是来测试性能的"}, {r, 123}]),
		db_mysql:update(test, [{row, "我是来测"}], [{id, 1}])
%%  		mysql:fetch(?DB_POOL, <<"insert into test(row,r) values ('我是来测试性能的',123)">>),
%% 		mysql:fetch(?DB_POOL, "insert into `test` set `row` = '我是来测试性能的', `r` = '123'"),
%% 		db_mysql:insert(test, [row, r], ["我是来测试性能的", 123]),		
%% 		mysql:fetch(?DB_POOL, "update test set `row` = '我是来测' where `id` = '1'")
%% 		mysql:prepare(?DB, insert_sql, <<"insert into test(row,r) values (?, ?)">>),
%% 		mysql:execute(?DB_POOL, insert_sql, ["我是来测试性能的", "123"]),
%%  		mysql:prepare(?DB, update_sql, <<"update test set row = ? where id = ?">>),
%% 		mysql:execute(?DB_POOL, update_sql, ["我是来", 1])
    end,
    run(F, 10000),
    mysql:fetch(?DB_POOL, <<"commit">>),

%    mysql:fetch(?DB, <<"begin">>),
%
%    F1 = fun() ->
%        mysql:fetch(?DB, io_lib:format(<<"update  `test` set  `row` = '~s' where id = ~p">>,["我是来测试性能的",123]))
%    end,
%    prof:run(F1, 10000),
%    mysql:fetch(?DB, <<"commit">>),
%
%    F2 = fun() ->
%        mysql:fetch(?DB, <<"select * from  `test` where id = 1">>)
%    end,
%    prof:run(F2, 10000),

ok.

run(Fun, Loop) -> 
    statistics(wall_clock),
    for(1, Loop, Fun),
    {_, T1} = statistics(wall_clock),
    io:format("~p loops, using time: ~pms~n", [Loop, T1]),
    ok.

for(Max, Max , Fun) ->
    Fun();
for(I, Max, Fun) -> 
    Fun(), for(I + 1, Max, Fun).

